package com.etrans.web.gps.business.report.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.report.domain.AbnomalVeVO;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.util.DateUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;

/**
 *问题车辆筛查Service
 * @author zhangw
 *
 */
@Service
public class AbnomalVehicleService extends BaseService{
	
	
	/**
	 * 根据区域id查询区域名称
	 * @return  
	 */
	public List<Integer> queryAreaListById(Integer area_id) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("FullID", String.format("%08d",area_id));
		return this.selectList("commonMapper.queryAreaIdById", param);
	}

	/**
	 * 根据业户分组查询异常车辆数
	 * @param queryContent 
	 * @param queryContent 
	 * @param areaId 
	 * @param areaList 权限区域列表
	 * @param enterprise_name
	 * @param monthTime 按日查询
	 * @return 1
	 */
	public Map<String,Object> queryBarChartByEnt(String timeType,String dateTime ,String queryType, String queryContent, 
			int areaId) throws Exception{
		//过滤条件
        DBObject match = new BasicDBObject();
		//时间限制条件
		if ("day".equals(timeType) && dateTime.length() == 10) {
			String inputTime = dateTime.substring(2,4)+dateTime.substring(5,7)+dateTime.substring(8,10);
			match.put("_id", Pattern.compile("^"+inputTime));
		}else if ("week".equals(timeType)) {
			String[] week = dateTime.split("-");
			Map<String, Object> dates = DateUtil.getYearAndWeekByDate(Integer.valueOf(week[0]), Integer.valueOf(week[1]));
			String Monday = dates.get("Monday")+" 00:00:00";
			String Sunday = dates.get("Sunday")+" 23:59:59";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			match.put("analyse_date", new BasicDBObject("$gte", sdf.parse(Monday)).append("$lte", sdf.parse(Sunday)));
		}else if ("mon".equals(timeType) && dateTime.length() == 7) {
			String inputTime = dateTime.substring(2,4)+dateTime.substring(5,7);
			match.put("_id", Pattern.compile("^"+inputTime));
		}
		//异常数量条件
      	match.put("exception_track_count", new BasicDBObject("$gte", 1));
      	if (StringUtils.isNumeric(queryContent)) {
      		if ("ent".equals(queryType)) {
      			match.put("enterprise_id", Integer.valueOf(queryContent));
    		}else if ("veh".equals(queryType)) {
    			match.put("vehicle_id", Integer.valueOf(queryContent));
    		}
      	}else {
      		match.put("area_id", new BasicDBObject("$in", this.queryAreaListById(areaId)));
      	}
		//分组
		DBObject group = new BasicDBObject("_id", "$enterprise_name");
		group.put("count", new BasicDBObject("$sum", 1));
		group.put("enterprise_id", new BasicDBObject("$first", "$enterprise_id"));
		//聚合参数
        List<Bson> bson = new ArrayList<Bson>();
        bson.add(new BasicDBObject("$match", match));
        bson.add(new BasicDBObject("$group", group));
        AggregateIterable<Document> documents = MGTemplete.getCollection(DBNAME, "vehicle_swap").aggregate(bson);
		List<String>  xAxisData =new ArrayList<String>();
		List<Integer>  SeriesData =new ArrayList<Integer>();
		List<Integer>  ids =new ArrayList<Integer>();
		for (Document doc : documents) {
			xAxisData.add(doc.getString("_id"));
			SeriesData.add(doc.getInteger("count"));
			ids.add(doc.getInteger("enterprise_id"));
		}
		Map<String,Object> resultMap =new HashMap<String, Object>();
		resultMap.put("xAxisData", xAxisData);
		resultMap.put("series", SeriesData);
		resultMap.put("entIds", ids);
		return resultMap;
	}

	/**
	 * 根据业户名和查询时间查询
	 * 
	 * @param timeType
	 * @param dateTime
	 * @param queryType
	 * @param queryContent
	 * @param areaId
	 * @param from
	 * @param size
	 * @return
	 * @throws Exception
	 */
	public List<AbnomalVeVO> getTableData(String timeType, String dateTime, String queryType, String queryContent, int areaId,
			int from, int size) throws Exception {
		//过滤条件
		BasicDBObject query = new BasicDBObject();
		//时间限制条件
		if ("day".equals(timeType) && dateTime.length() == 10) {
			String inputTime = dateTime.substring(2,4)+dateTime.substring(5,7)+dateTime.substring(8,10);
			query.put("_id", Pattern.compile("^"+inputTime));
		}else if ("week".equals(timeType)) {
			String[] week = dateTime.split("-");
			Map<String, Object> dates = DateUtil.getYearAndWeekByDate(Integer.valueOf(week[0]), Integer.valueOf(week[1]));
			String Monday = dates.get("Monday")+" 00:00:00";
			String Sunday = dates.get("Sunday")+" 23:59:59";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			query.put("analyse_date", new BasicDBObject("$gte", sdf.parse(Monday)).append("$lte", sdf.parse(Sunday)));
		}else if ("mon".equals(timeType) && dateTime.length() == 7) {
			String inputTime = dateTime.substring(2,4)+dateTime.substring(5,7);
			query.put("_id", Pattern.compile("^"+inputTime));
		}
		//异常数量条件
		query.put("exception_track_count", new BasicDBObject("$gte", 1));
      	if (StringUtils.isNumeric(queryContent)) {
      		if ("ent".equals(queryType)) {
      			query.put("enterprise_id", Integer.valueOf(queryContent));
    		}else if ("veh".equals(queryType)) {
    			query.put("vehicle_id", Integer.valueOf(queryContent));
    		}
      	}else {
      		query.put("area_id", new BasicDBObject("$in", this.queryAreaListById(areaId)));
      	}
      	Bson filter = new BasicDBObject(query);
      	Bson sort = new BasicDBObject("overspeed_100_count", -1);
      	FindIterable<Document> documents = 
      			MGTemplete.getCollection(DBNAME, "vehicle_swap").find(filter).sort(sort).skip(from).limit(size);
      	List<AbnomalVeVO> list = new ArrayList<>();
		for (Document doc : documents) {
			list.add(toBean(doc, AbnomalVeVO.class));
		}
		return list;
	}

	/**
	 * 根据业户名和查询时间查询
	 * 
	 * @param timeType
	 * @param dateTime
	 * @param queryType
	 * @param queryContent
	 * @param areaId
	 * @return 登录用户权限下的全部业户的问题车辆
	 * @throws Exception
	 */
	public int getTableDataCount(String timeType, String dateTime, String queryType, String queryContent,
			int areaId) throws Exception {
		//过滤条件
		BasicDBObject query = new BasicDBObject();
		//时间限制条件
		if ("day".equals(timeType) && dateTime.length() == 10) {
			String inputTime = dateTime.substring(2,4)+dateTime.substring(5,7)+dateTime.substring(8,10);
			query.put("_id", Pattern.compile("^"+inputTime));
		}else if ("week".equals(timeType)) {
			String[] week = dateTime.split("-");
			Map<String, Object> dates = DateUtil.getYearAndWeekByDate(Integer.valueOf(week[0]), Integer.valueOf(week[1]));
			String Monday = dates.get("Monday")+" 00:00:00";
			String Sunday = dates.get("Sunday")+" 23:59:59";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			query.put("analyse_date", new BasicDBObject("$gte", sdf.parse(Monday)).append("$lte", sdf.parse(Sunday)));
		}else if ("mon".equals(timeType) && dateTime.length() == 7) {
			String inputTime = dateTime.substring(2,4)+dateTime.substring(5,7);
			query.put("_id", Pattern.compile("^"+inputTime));
		}
		//异常数量条件
		query.put("exception_track_count", new BasicDBObject("$gte", 1));
      	if (StringUtils.isNumeric(queryContent)) {
      		if ("ent".equals(queryType)) {
      			query.put("enterprise_id", Integer.valueOf(queryContent));
    		}else if ("veh".equals(queryType)) {
    			query.put("vehicle_id", Integer.valueOf(queryContent));
    		}
      	}else {
      		query.put("area_id", new BasicDBObject("$in", this.queryAreaListById(areaId)));
      	}
      	Long count = MGTemplete.getCollection(DBNAME, "vehicle_swap").count(new BasicDBObject(query));
		return count.intValue();
	}
	
	/**
	 * 
	 * @param document
	 * @param clazz
	 * @return
	 */
	public static <T> T toBean(Document document, Class<T> clazz) {
        String json = JSONObject.toJSONString(document);
        return JSONObject.toJavaObject(JSONObject.parseObject(json), clazz);
    }
}
